﻿using System;

namespace configstore.CSM.Common
{
    using TouchSocket.Core;
    using TouchSocket.Http;
    internal abstract class ConfigStorePluginBase : PluginBase, IHttpPlugin
    {
        public ConfigStorePluginBase(): base() { }

        public async Task OnHttpRequest(IHttpSessionClient client, HttpContextEventArgs e)
        {
            if (! e.Context.Request.UrlEquals(ListenUri))
            {
                await e.InvokeNext();
            }
            else
            {
                int err_times = 0;
                while (true)
                {
                    try
                    {
                        var session = new ConfigStoreSession(client, e);
                        await OnRequest(session);
                        break;
                    }
                    catch (Exception ex)
                    {
                        err_times++;

                        Console.WriteLine(ex.Message);
                        if (err_times > 99)
                        {
                            await e.Context.Response.SetStatus(200, ex.Message)
                                .FromObj(new
                                {
                                    success = false,
                                    error = true,
                                    param = new
                                    {
                                        msg = ex.Message
                                    }
                                }).AnswerAsync();
                            break;
                        }
                        await Task.Delay(60);
                    }
                }
            }
        }
        protected override void Dispose(bool disposing)
        {
        }

        protected abstract Task OnRequest(ConfigStoreSession session);
        protected abstract string ListenUri { get; }
    }
}
